package com.tianhua.javs.core.func.script;

import com.tianhua.javs.client.bean.JavsSegmentBean;
import com.tianhua.javs.client.bean.ScriptVarMappingBean;
import com.tianhua.javs.client.bean.TranslateResultBean;
import com.tianhua.javs.client.enums.VariablePoolTypeEnum;
import com.tianhua.javs.client.func.IScriptFunc;
import com.tianhua.javs.client.func.ITranslatorFunc;
import com.tianhua.javs.core.func.TranslatorContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Description:赋值函数
 * date: 2022/2/13
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Component(value = "assignFunc")
public class AssignFunc  implements IScriptFunc {
    @Autowired
    private TranslatorContainer translatorContainer;

    @Override
    public TranslateResultBean translate(String keyWardStr, Map<String, List<ScriptVarMappingBean>> javsVarMap) {

        String tempSegment = replace(javsVarMap.get(VariablePoolTypeEnum.JAVA_SDK.getCode()), JavsSegmentBean.getInstance(keyWardStr,"",""));
        JavsSegmentBean javsSegmentBean = null;
        Component component = AssignFunc.class.getAnnotation(Component.class);
        List<ITranslatorFunc> translatorFuncList = translatorContainer.getByScriptFuncBean(component.value());
        for (ITranslatorFunc translatorFunc : translatorFuncList) {
            javsSegmentBean = translatorFunc.translate(tempSegment);
            //如果函数匹配到则不再进行后续的匹配内容
            if(javsSegmentBean.match()){
                break;
            }
        }
        return TranslateResultBean.getInstance(javsSegmentBean);
    }


    private String replace(List<ScriptVarMappingBean> javsVarList, JavsSegmentBean javsSegmentBean) {
        String tempSegment = javsSegmentBean.getSegment();
        for (ScriptVarMappingBean scriptVarMappingBean : javsVarList) {
            //无差别替换
            tempSegment = tempSegment.replace(scriptVarMappingBean.getJavsVarCode() + javsSegmentBean.getKeySuffix(), scriptVarMappingBean.getJavaCode() + javsSegmentBean.getValueSuffix());
        }
        return tempSegment;
    }
}
